package vooga.xml.handlers;

import vooga.xml.XMLException;


public class FactoryHandler extends vooga.xml.XMLHandler
{
    // BUGBUG -- find a way to factor these names out
    public static final String VALUE_ATTRIBUTE = "value";
    public static final String CLASS_ATTRIBUTE = "class";


    public Object handleNode (org.w3c.dom.Node node, Object context) throws XMLException
    {
        try
        {
            Object[] args = null;
            if (isComplete(node))
            {
                args = new Object[] { getAttribute(node, VALUE_ATTRIBUTE) };
            }
            else
            {
                java.util.List paramNodes = getSubNodes(node);
                args = new Object[paramNodes.size()];
                for (int k = 0; k < args.length; k++)
                {
                    org.w3c.dom.Node current = (org.w3c.dom.Node)paramNodes.get(k);
                    args[k] = getDocument().getHandler(current.getNodeName()).handleNode(current, null);
                }
            }
	    return vooga.util.Reflection.createInstance(getAttribute(node, CLASS_ATTRIBUTE), args);
        }
        catch (vooga.util.ReflectionException e)
        {
            throw new vooga.xml.XMLException("Could not handle " + node, e);
        }
    }


    protected boolean isComplete (org.w3c.dom.Node node)
    {
        return (getAttribute(node, VALUE_ATTRIBUTE) != null);
    }
}
